package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.utils.AddressUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.system.domain.HatchetAcq;
import com.ruoyi.system.domain.HatchetAgent;
import com.ruoyi.system.domain.HatchetIssBank;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.domain.HatchetMessage;
import com.ruoyi.system.domain.HatchetMoneyChange;
import com.ruoyi.system.domain.HatchetOrderPayment;
import com.ruoyi.system.domain.UserRelation;
import com.ruoyi.system.service.IHatchetAcqService;
import com.ruoyi.system.service.IHatchetAgentService;
import com.ruoyi.system.service.IHatchetIssBankService;
import com.ruoyi.system.service.IHatchetMerchantService;
import com.ruoyi.system.service.IHatchetMessageService;
import com.ruoyi.system.service.IHatchetMoneyChangeService;
import com.ruoyi.system.service.IHatchetOrderPaymentService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.IUserRelationService;
import com.ruoyi.system.vo.StringUtilsss;

/**
 * 订单 信息操作处理
 * 
 * @author xj
 * @date 2019-02-20
 */
@Controller
@RequestMapping("/system/hatchetOrderPayment")
public class HatchetOrderPaymentController extends BaseController {
	private String prefix = "system/hatchetOrderPayment";

	@Autowired
	private IHatchetOrderPaymentService hatchetOrderPaymentService;
	@Autowired
	private IHatchetMerchantService hatchetMerchantService;
	@Autowired
	private IHatchetAgentService hatchetAgentService;
	@Autowired
	private IHatchetIssBankService issBankService;
	@Autowired
	private ISysDictDataService sysDictDataService;
	@Autowired
	private IHatchetAcqService hatchetAcqService;
	@Autowired
	private IHatchetMoneyChangeService changeService;
	@Autowired
	private IHatchetMessageService messageService;
	@Autowired
	private IUserRelationService relationService;

	@RequiresPermissions("system:hatchetOrderPayment:view")
	@GetMapping("/{status}")
	public String hatchetOrderPayment(@PathVariable("status") Integer status) {
		if (status == 1) {
			return prefix + "/hatchetOrderPayment";
		} else if (status == 2) {
			return prefix + "/hatchetOrderPayment1";
		} else if (status == 3) {
			return prefix + "/zhenxinPag";
		}
		return null;
	}

	/**
	 * 跳转当日总交易量
	 * 
	 * @return
	 */
	@GetMapping("/toAmount")
	public String toAmount() {
		return "system/amount";
	}
	
	/**
	 * 订单详情
	 */
	@GetMapping("/detail/{iD}")
	public String deatil(@PathVariable("iD") String iD, ModelMap mmap)
	{
		HatchetOrderPayment hatchetOrderPayment = hatchetOrderPaymentService.selectHatchetOrderPaymentById(iD);
		mmap.put("hatchetOrderPayment", hatchetOrderPayment);
	    return prefix + "/detail";
	}
	
	/**
	 * 管理员查看当日总交易量
	 * 
	 * @return
	 */
	@ResponseBody
	@PostMapping("/selectAmount")
	@RequiresPermissions("system:amount:view")
	public List<HatchetOrderPayment> selectAmount() {
		// 重新组装每日收益
		HatchetOrderPayment orderPayment = new HatchetOrderPayment();
		Map<String, Object> params1 = new HashMap<String, Object>();
		params1.put("beginTime", DateUtils.getNextDateStr(-9));
		params1.put("endTime", DateUtils.getNextDateStr(0));
		orderPayment.setParams(params1);
		orderPayment.setSTATUS("10B");// 只查询交易成功的
	    List<HatchetOrderPayment> selectHatchetOrderPaymentMoneyByDay = hatchetOrderPaymentService.selectHatchetOrderPaymentMoneyByDay(orderPayment);
		/*for (HatchetOrderPayment hatchetOrderPayment : selectHatchetOrderPaymentMoneyByDay) {
			hatchetOrderPayment.setTime(hatchetOrderPayment);
		}*/
	/*	// 查询一周的数据
		for (int i = -6; i < 1; i++) {
			Map<String, Object> params1 = new HashMap<String, Object>();
			params1.put("beginTime", DateUtils.getNextDateStr(i));
			params1.put("endTime", DateUtils.getNextDateStr(i));
			orderPayment.setParams(params1);
			
			BigDecimal sumAmount = hatchetOrderPaymentService.selectSumMoney(orderPayment);
			HatchetOrderPayment orderPaymentForWeek = new HatchetOrderPayment();
			orderPaymentForWeek.setTime(DateUtils.getNextDateStr(i));
			BigDecimal b2 = new BigDecimal(Double.toString(10000));
			BigDecimal trxAmt = sumAmount.divide(b2, 6, BigDecimal.ROUND_HALF_UP);
			orderPaymentForWeek.setTrxAmt(trxAmt);
			// 查看交易笔数
			Long orderPaymentCount = hatchetOrderPaymentService.selectOrderPaymentCount(orderPayment);
			// 设置交易笔数
			orderPaymentForWeek.setProcessingCode(orderPaymentCount + "");
			list.add(orderPaymentForWeek);
		}*/
	    for (HatchetOrderPayment hatchetOrderPayment : selectHatchetOrderPaymentMoneyByDay) {
	    	hatchetOrderPayment.setTime(DateUtils.dateToStrLong(hatchetOrderPayment.getCompleteTime(), "yy-MM-dd"));
		}
		return selectHatchetOrderPaymentMoneyByDay;
	}

	/**
	 * 查询订单列表
	 */
	@RequiresPermissions("system:hatchetOrderPayment:list")
	@PostMapping("/list/{status}")
	@ResponseBody
	public TableDataInfo list(HatchetOrderPayment hatchetOrderPayment) {
		// 通过商户编号或者
		if (StringUtils.isNotEmpty(hatchetOrderPayment.getMerchantNo())) {
			HatchetMerchant merchant = hatchetMerchantService
					.selectHatchetMerchantByNo(hatchetOrderPayment.getMerchantNo());
			if (StringUtils.isNotNull(merchant)) {
				hatchetOrderPayment.setMerchantId(merchant.getID());
			} else {
				return getDataTable(new ArrayList<>());
			}
			// 代理编号查询交易
		}
		if (StringUtils.isNotEmpty(hatchetOrderPayment.getAgentNo())) {
			HatchetAgent agent1 = hatchetAgentService.selectHatchetAgentByNo(hatchetOrderPayment.getAgentNo());
			if (StringUtils.isNotNull(agent1)) {
				// 查代理商直接
				if (hatchetOrderPayment.getDirect() == 1) {
					hatchetOrderPayment.setAgentId(agent1.getID());
					// 查所有
				} else {
					hatchetOrderPayment.setDepartmentCode(StringUtils.likeDepartmentCode(agent1.getDepartmentCode()));
				}
			} else {
				return getDataTable(new ArrayList<>());
			}
		}
		int index = 0;
		startPage();
		List<HatchetOrderPayment> list = hatchetOrderPaymentService.selectOrderPaymentForKefu(hatchetOrderPayment);
		for (HatchetOrderPayment hatchetOrderPayment2 : list) {
			if (index == 0) {
				BigDecimal sumMoney = hatchetOrderPaymentService.selectSumMoneyForKefu(hatchetOrderPayment);
				hatchetOrderPayment2.setSumMoney(sumMoney);
				index++;
			}
			if (hatchetOrderPayment2.getMerchantId() != null) {
				HatchetMerchant hatchetMerchant = hatchetMerchantService
						.selectHatchetMerchantById(hatchetOrderPayment2.getMerchantId());
				if (hatchetMerchant != null) {
					hatchetOrderPayment2.setMerchantNo(hatchetMerchant.getMerchantNo());
					hatchetOrderPayment2.setMerchantName(hatchetMerchant.getMerchantCnName());
				}
			}
			if (hatchetOrderPayment2.getAgentId() != null) {
				HatchetAgent agent = hatchetAgentService.selectHatchetAgentById(hatchetOrderPayment2.getAgentId());
				if (agent != null) {
					hatchetOrderPayment2.setAgentNo(agent.getAgentNo());
					hatchetOrderPayment2.setAgentName(agent.getAgentName());
				}
			}
			if (hatchetOrderPayment2.getIssBankId() != null) {
				HatchetIssBank issBank = issBankService.selectHatchetIssBankById(hatchetOrderPayment2.getIssBankId());
				if (issBank != null) {
					hatchetOrderPayment2.setIssBankId(issBank.getShortCnName());
				}
			}
			// 获取通道信息
			if (hatchetOrderPayment2.getAcqId() != null) {
				HatchetAcq hatchetAcq = hatchetAcqService.selectHatchetAcqById(hatchetOrderPayment2.getAcqId());
				if (hatchetAcq != null) {
					hatchetOrderPayment2.setAcqNo(hatchetAcq.getAcqCode());
					hatchetOrderPayment2.setAcqName(hatchetAcq.getAcqName());
				}
			}
		}
		return getDataTable(list);
	}

	/**
	 * 导出订单列表
	 */
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(HatchetOrderPayment hatchetOrderPayment) {
		ExcelUtil<HatchetOrderPayment> util = new ExcelUtil<HatchetOrderPayment>(HatchetOrderPayment.class);
		// 通过商户编号或者
		if (StringUtils.isNotEmpty(hatchetOrderPayment.getMerchantNo())) {
			HatchetMerchant merchant = hatchetMerchantService
					.selectHatchetMerchantByNo(hatchetOrderPayment.getMerchantNo());
			if (StringUtils.isNotNull(merchant)) {
				hatchetOrderPayment.setMerchantId(merchant.getID());
			} else {
				return util.exportExcel(new ArrayList<>(), "订单列表");
			}
			// 代理编号查询交易
		} else if (StringUtils.isNotEmpty(hatchetOrderPayment.getAgentNo())) {
			HatchetAgent agent1 = hatchetAgentService.selectHatchetAgentByNo(hatchetOrderPayment.getAgentNo());
			if (StringUtils.isNotNull(agent1)) {
				// 查代理商直接
				if (hatchetOrderPayment.getDirect() == 1) {
					hatchetOrderPayment.setAgentId(agent1.getID());
					// 查所有
				} else {
					hatchetOrderPayment.setDepartmentCode(StringUtils.likeDepartmentCode(agent1.getDepartmentCode()));
				}
			} else {
				return util.exportExcel(new ArrayList<>(), "订单列表");
			}
		}
		List<HatchetOrderPayment> list = hatchetOrderPaymentService.selectOrderPaymentForDLS(hatchetOrderPayment);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (HatchetOrderPayment hatchetOrderPayment2 : list) {
			hatchetOrderPayment2.setTime(sdf.format(hatchetOrderPayment2.getCompleteTime()));
			hatchetOrderPayment2.setSettleListStatus(sysDictDataService.selectDictLabel("settleList_status",
					hatchetOrderPayment2.getSettleListStatus()));
			hatchetOrderPayment2
					.setSTATUS(sysDictDataService.selectDictLabel("trade_status", hatchetOrderPayment2.getSTATUS()));
			hatchetOrderPayment2.setTradeType(
					sysDictDataService.selectDictLabel("trade_type", hatchetOrderPayment2.getTradeType()));
			if (hatchetOrderPayment2.getMerchantId() != null) {
				HatchetMerchant hatchetMerchant = hatchetMerchantService
						.selectHatchetMerchantById(hatchetOrderPayment2.getMerchantId());
				if (hatchetMerchant != null) {
					hatchetOrderPayment2.setMerchantNo(hatchetMerchant.getMerchantNo());
					hatchetOrderPayment2.setMerchantName(hatchetMerchant.getMerchantCnName());
				}
			}
			if (hatchetOrderPayment2.getAgentId() != null) {
				HatchetAgent agent = hatchetAgentService.selectHatchetAgentById(hatchetOrderPayment2.getAgentId());
				if (agent != null) {
					hatchetOrderPayment2.setAgentNo(agent.getAgentNo());
					hatchetOrderPayment2.setAgentName(agent.getAgentName());
				}
			}
			if (hatchetOrderPayment2.getIssBankId() != null) {
				HatchetIssBank issBank = issBankService.selectHatchetIssBankById(hatchetOrderPayment2.getIssBankId());
				if (issBank != null) {
					hatchetOrderPayment2.setIssBankId(issBank.getShortCnName());
				}
			}
			if (hatchetOrderPayment2.getAcqId() != null) {
				HatchetAcq hatchetAcq = hatchetAcqService.selectHatchetAcqById(hatchetOrderPayment2.getAcqId());
				if (hatchetAcq != null) {
					hatchetOrderPayment2.setAcqNo(hatchetAcq.getAcqCode());
					hatchetOrderPayment2.setAcqName(hatchetAcq.getAcqName());
				}
			}
		}
		return util.exportExcel(list, "订单列表");

	}

	/**
	 * 查询订单列表(还款，养卡记录)
	 */
	@RequiresPermissions("system:hatchetOrderPayment:list")
	@PostMapping("/list1")
	@ResponseBody
	public TableDataInfo list1(HatchetOrderPayment hatchetOrderPayment) {
		// 通过商户编号或者代理编号查询交易
		HatchetAgent agent1 = hatchetAgentService.selectHatchetAgentByNo(hatchetOrderPayment.getAgentNo());
		if (agent1 != null) {
			hatchetOrderPayment.setAgentId(agent1.getID());
		}
		HatchetMerchant merchant = hatchetMerchantService
				.selectHatchetMerchantByNo(hatchetOrderPayment.getMerchantNo());
		if (merchant != null) {
			hatchetOrderPayment.setMerchantId(merchant.getID());
		}
		// BigDecimal sumMoney =
		// hatchetOrderPaymentService.selectSumMoney(hatchetOrderPayment);
		BigDecimal sumMoney = hatchetOrderPaymentService.selectSumMoneyForPlan(hatchetOrderPayment);
		int index = 0;
		startPage();
		List<HatchetOrderPayment> list = hatchetOrderPaymentService.selectOrderPaymentByTrade(hatchetOrderPayment);
		for (HatchetOrderPayment hatchetOrderPayment2 : list) {
			if (index == 0) {
				hatchetOrderPayment2.setSumMoney(sumMoney);
				index++;
			}
			if (hatchetOrderPayment2.getMerchantId() != null) {
				HatchetMerchant hatchetMerchant = hatchetMerchantService
						.selectHatchetMerchantById(hatchetOrderPayment2.getMerchantId());
				if (hatchetMerchant != null) {
					hatchetOrderPayment2.setMerchantNo(hatchetMerchant.getMerchantNo());
					hatchetOrderPayment2.setMerchantName(hatchetMerchant.getMerchantCnName());
				}
			}
			if (hatchetOrderPayment2.getAgentId() != null) {
				HatchetAgent agent = hatchetAgentService.selectHatchetAgentById(hatchetOrderPayment2.getAgentId());
				if (agent != null) {
					hatchetOrderPayment2.setAgentNo(agent.getAgentNo());
					hatchetOrderPayment2.setAgentName(agent.getAgentName());
				}
			}
			if (hatchetOrderPayment2.getIssBankId() != null) {
				HatchetIssBank issBank = issBankService.selectHatchetIssBankById(hatchetOrderPayment2.getIssBankId());
				if (issBank != null) {
					hatchetOrderPayment2.setIssBankId(issBank.getShortCnName());
				}
			}
			if (hatchetOrderPayment2.getAcqId() != null) {
				HatchetAcq hatchetAcq = hatchetAcqService.selectHatchetAcqById(hatchetOrderPayment2.getAcqId());
				if (hatchetAcq != null) {
					hatchetOrderPayment2.setAcqNo(hatchetAcq.getAcqCode());
					hatchetOrderPayment2.setAcqName(hatchetAcq.getAcqName());
				}
			}
		}
		return getDataTable(list);
	}

	/**
	 * 查询订单列表(卡测评，征信)
	 */
	@RequiresPermissions("system:hatchetOrderPayment:list")
	@PostMapping("/zhengxinList")
	@ResponseBody
	public TableDataInfo zhengxinList(HatchetOrderPayment hatchetOrderPayment) {
		// 通过商户编号查询交易
		HatchetMerchant merchant = hatchetMerchantService
				.selectHatchetMerchantByNo(hatchetOrderPayment.getMerchantNo());
		if (merchant != null) {
			hatchetOrderPayment.setMerchantId(merchant.getID());
		}
		BigDecimal sumMoney = hatchetOrderPaymentService.selectZXSumMoney(hatchetOrderPayment);
		int index = 0;
		startPage();
		List<HatchetOrderPayment> list = hatchetOrderPaymentService.selectOrderPaymentZX(hatchetOrderPayment);
		for (HatchetOrderPayment hatchetOrderPayment2 : list) {
			if (index == 0) {
				hatchetOrderPayment2.setSumMoney(sumMoney);
				index++;
			}
			if (hatchetOrderPayment2.getMerchantId() != null) {
				HatchetMerchant hatchetMerchant = hatchetMerchantService
						.selectHatchetMerchantById(hatchetOrderPayment2.getMerchantId());
				if (hatchetMerchant != null) {
					hatchetOrderPayment2.setMerchantNo(hatchetMerchant.getMerchantNo());
					hatchetOrderPayment2.setMerchantName(hatchetMerchant.getMerchantCnName());
				}
			}
		}
		return getDataTable(list);
	}

	/**
	 * 卡测评/征信分润下发
	 */
	@RequiresPermissions("system:hatchetOrderPayment:remove")
	@Log(title = "分润下发", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	@Transactional
	public AjaxResult remove(String ids) {
		List<String> result = Arrays.asList(ids.split(","));
		// 依次由黄金会员---联创
		String rate1 = sysDictDataService.selectDictLabel("ZXCP_rate", "1");
		String rate2 = sysDictDataService.selectDictLabel("ZXCP_rate", "2");
		String rate3 = sysDictDataService.selectDictLabel("ZXCP_rate", "3");
		String rate4 = sysDictDataService.selectDictLabel("ZXCP_rate", "4");
		String rate5 = sysDictDataService.selectDictLabel("ZXCP_rate", "5");
		for (String string : result) {
			HatchetOrderPayment orderPayment = hatchetOrderPaymentService.selectHatchetOrderPaymentById(string);
			if ("10A".equals(orderPayment.getSettleListStatus())) {
				// 减去成本
				BigDecimal money = null;
				if ("CP".equals(orderPayment.getTradeType())) {
					money = orderPayment.getTrxAmt().subtract(new BigDecimal("8"));
				} else if ("ZX".equals(orderPayment.getTradeType())) {
					money = orderPayment.getTrxAmt().subtract(new BigDecimal("10"));
				}
				BigDecimal money1 = money.multiply(new BigDecimal(rate1)).setScale(2, BigDecimal.ROUND_HALF_UP);
				BigDecimal money2 = money.multiply(new BigDecimal(rate2)).setScale(2, BigDecimal.ROUND_HALF_UP);
				BigDecimal money3 = money.multiply(new BigDecimal(rate3)).setScale(2, BigDecimal.ROUND_HALF_UP);
				BigDecimal money4 = money.multiply(new BigDecimal(rate4)).setScale(2, BigDecimal.ROUND_HALF_UP);
				BigDecimal money5 = money.multiply(new BigDecimal(rate5)).setScale(2, BigDecimal.ROUND_HALF_UP);

				if (orderPayment.getMerchantId() != null) {
					// 获取商户的信息
					HatchetMerchant mer = hatchetMerchantService
							.selectHatchetMerchantById(orderPayment.getMerchantId());
					HatchetAgent agent = hatchetAgentService.selectHatchetAgentById(mer.getAgentId());

					if (mer != null) {
						BigDecimal aa = new BigDecimal("0");
						String msg = null;
						String msg1 = null;
						String moneyType = null;
						if ("ZX".equals(orderPayment.getTradeType())) {
							msg1 = "征信查询收益";
							moneyType = "10Z";
						} else if ("CP".equals(orderPayment.getTradeType())) {
							msg1 = "卡测评收益";
							moneyType = "10W";
						}
						// 通过代理商等级获取经纪人对其收益,肯定存在经纪人对其分润，代理商获取分润差。
						if ("1".equals(agent.getTYPE())) {
							aa = money3;
						}
						if ("2".equals(agent.getTYPE())) {
							aa = money4.add(money3);
						}
						if ("3".equals(agent.getTYPE())) {
							aa = money5.add(money4).add(money3);
						}

						UserRelation userRelation1 = new UserRelation();
						userRelation1.setUid(mer.getID());
						userRelation1.setCreateTime(orderPayment.getCreateTime());
						UserRelation userRelation = relationService.findByTime(userRelation1);
						if (userRelation != null) {

							if ("3".equals(userRelation.getLevel())) {
								money = money1.add(money2);
								HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
										"10B", moneyType, money, mer.getMerchantNo(), orderPayment.getOrderNo(), "10B",
										new Date());
								changeService.insertHatchetMoneyChange(moneyChange);
								if ("ZX".equals(orderPayment.getTradeType())) {
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过征信查询为您贡献收益" + money
											+ "元!";
								} else if ("CP".equals(orderPayment.getTradeType())) {
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过卡测评为您贡献收益" + money
											+ "元!";
								}
								HatchetMessage hatchetMessage = new HatchetMessage(StringUtilsss.randomUUID(), msg1,
										msg, "5", "0", mer.getID(), mer.getPHONE(), mer.getID(), new Date(), money + "",
										null, null);
								messageService.insertHatchetMessage(hatchetMessage);
								mer.setTotalMoney(mer.getTotalMoney().add(money));

								// 通过代理商等级获取经纪人对其分润
								mer.setExamineResult(AddressUtils.contributeMoney(mer.getExamineResult(), aa,
										AddressUtils.INCOME_JF));
								mer.setChinaRegionId(AddressUtils.contributeMoney(mer.getChinaRegionId(), aa,
										AddressUtils.INCOME_JF));
								hatchetMerchantService.updateHatchetMerchant(mer);
							}

							if ("2".equals(userRelation.getLevel())) {
								// 自己拿2-1的分润
								HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
										"10B", moneyType, money1, mer.getMerchantNo(), orderPayment.getOrderNo(), "10B",
										new Date());
								changeService.insertHatchetMoneyChange(moneyChange);
								if ("ZX".equals(orderPayment.getTradeType())) {
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过征信查询为您贡献收益" + money1
											+ "元!";
								} else if ("CP".equals(orderPayment.getTradeType())) {
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过卡测评为您贡献收益" + money1
											+ "元!";
								}
								HatchetMessage hatchetMessage = new HatchetMessage(StringUtilsss.randomUUID(), msg1,
										msg, "5", "0", mer.getID(), mer.getPHONE(), mer.getID(), new Date(),
										money1 + "", null, null);
								messageService.insertHatchetMessage(hatchetMessage);
								mer.setTotalMoney(mer.getTotalMoney().add(money1));
								hatchetMerchantService.updateHatchetMerchant(mer);

								// 经纪人拿3-2的分润
								HatchetMerchant merchant = hatchetMerchantService
										.selectHatchetMerchantById(userRelation.getU2id());
								HatchetMoneyChange moneyChange1 = new HatchetMoneyChange(StringUtilsss.randomUUID(),
										"10B", moneyType, money2, merchant.getMerchantNo(), orderPayment.getOrderNo(),
										"10B", new Date());
								changeService.insertHatchetMoneyChange(moneyChange1);
								if ("ZX".equals(orderPayment.getTradeType())) {
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过征信查询为您贡献收益" + money2
											+ "元!";
								} else if ("CP".equals(orderPayment.getTradeType())) {
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过卡测评为您贡献收益" + money2
											+ "元!";
								}

								HatchetMessage hatchetMessage1 = new HatchetMessage(StringUtilsss.randomUUID(), msg1,
										msg, "5", "0", merchant.getID(), merchant.getPHONE(), merchant.getID(),
										new Date(), money2 + "", null, null);
								messageService.insertHatchetMessage(hatchetMessage1);
								merchant.setTotalMoney(merchant.getTotalMoney().add(money2));

								// 通过代理商等级获取经纪人对其分润
								merchant.setExamineResult(AddressUtils.contributeMoney(merchant.getExamineResult(), aa,
										AddressUtils.INCOME_JF));
								merchant.setChinaRegionId(AddressUtils.contributeMoney(merchant.getChinaRegionId(), aa,
										AddressUtils.INCOME_JF));
								hatchetMerchantService.updateHatchetMerchant(merchant);

							}

							if ("1".equals(userRelation.getLevel())) {
								// uid1拿2-1的分润,黄金会员的值
								HatchetMerchant merchant = hatchetMerchantService
										.selectHatchetMerchantById(userRelation.getU1id());
								HatchetMerchant merchant2 = hatchetMerchantService
										.selectHatchetMerchantById(userRelation.getU2id());
								if (merchant != null) {
									// 黄金会员
									HatchetMoneyChange moneyChange1 = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", moneyType, money1, merchant.getMerchantNo(), orderPayment.getOrderNo(),
											"10B", new Date());
									changeService.insertHatchetMoneyChange(moneyChange1);
									if ("ZX".equals(orderPayment.getTradeType())) {
										msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过征信查询为您贡献收益"
												+ money1 + "元!";
									} else if ("CP".equals(orderPayment.getTradeType())) {
										msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过卡测评为您贡献收益"
												+ money1 + "元!";
									}
									HatchetMessage hatchetMessage1 = new HatchetMessage(StringUtilsss.randomUUID(),
											msg1, msg, "5", "0", merchant.getID(), merchant.getPHONE(),
											merchant.getID(), new Date(), money1 + "", null, null);
									messageService.insertHatchetMessage(hatchetMessage1);
									merchant.setTotalMoney(merchant.getTotalMoney().add(money1));
									hatchetMerchantService.updateHatchetMerchant(merchant);
									// 经纪人
									HatchetMoneyChange moneyChange2 = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", moneyType, money2, merchant2.getMerchantNo(), orderPayment.getOrderNo(),
											"10B", new Date());
									changeService.insertHatchetMoneyChange(moneyChange2);
									if ("ZX".equals(orderPayment.getTradeType())) {
										msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过征信查询为您贡献收益"
												+ money2 + "元!";
									} else if ("CP".equals(orderPayment.getTradeType())) {
										msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过卡测评为您贡献收益"
												+ money2 + "元!";
									}
									HatchetMessage hatchetMessage2 = new HatchetMessage(StringUtilsss.randomUUID(),
											msg1, msg, "5", "0", merchant2.getID(), merchant2.getPHONE(),
											merchant2.getID(), new Date(), money2 + "", null, null);
									messageService.insertHatchetMessage(hatchetMessage2);
									merchant2.setTotalMoney(merchant2.getTotalMoney().add(money2));

									// 通过代理商等级获取经纪人对其分润
									merchant2.setExamineResult(AddressUtils
											.contributeMoney(merchant2.getExamineResult(), aa, AddressUtils.INCOME_JF));
									merchant2.setChinaRegionId(AddressUtils
											.contributeMoney(merchant2.getChinaRegionId(), aa, AddressUtils.INCOME_JF));
									hatchetMerchantService.updateHatchetMerchant(merchant2);

								} else {
									money = money1.add(money2);
									HatchetMoneyChange moneyChange2 = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", moneyType, money, merchant2.getMerchantNo(), orderPayment.getOrderNo(),
											"10B", new Date());
									changeService.insertHatchetMoneyChange(moneyChange2);
									if ("ZX".equals(orderPayment.getTradeType())) {
										msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过征信查询为您贡献收益"
												+ money + "元!";
									} else if ("CP".equals(orderPayment.getTradeType())) {
										msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过卡测评为您贡献收益" + money
												+ "元!";
									}
									HatchetMessage hatchetMessage2 = new HatchetMessage(StringUtilsss.randomUUID(),
											msg1, msg, "5", "0", merchant2.getID(), merchant2.getPHONE(),
											merchant2.getID(), new Date(), money + "", null, null);
									messageService.insertHatchetMessage(hatchetMessage2);
									merchant2.setTotalMoney(merchant2.getTotalMoney().add(money));

									// 通过代理商等级获取经纪人对其分润
									merchant2.setExamineResult(AddressUtils
											.contributeMoney(merchant2.getExamineResult(), aa, AddressUtils.INCOME_JF));
									merchant2.setChinaRegionId(AddressUtils
											.contributeMoney(merchant2.getChinaRegionId(), aa, AddressUtils.INCOME_JF));
									hatchetMerchantService.updateHatchetMerchant(merchant2);
								}
							}

							// 代理商分润
							BigDecimal agentMoney;
							if (!"null".equals(userRelation.getU3id())) {
								// 运营商分润
								HatchetAgent agent1 = hatchetAgentService
										.selectHatchetAgentById(userRelation.getU3id());
								HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
										"10B", moneyType, money3, agent1.getAgentNo(), orderPayment.getOrderNo(), "10B",
										new Date());
								changeService.insertHatchetMoneyChange(moneyChange);
								agent1.setTotalMoney(agent1.getTotalMoney().add(money3));
								hatchetAgentService.updateHatchetAgent(agent1);
							}

							if (!"null".equals(userRelation.getU4id())) {
								if (!"null".equals(userRelation.getU3id())) {
									HatchetAgent agent1 = hatchetAgentService
											.selectHatchetAgentById(userRelation.getU4id());
									HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", moneyType, money4, agent1.getAgentNo(), orderPayment.getOrderNo(), "10B",
											new Date());
									changeService.insertHatchetMoneyChange(moneyChange);
									agent1.setTotalMoney(agent1.getTotalMoney().add(money4));
									hatchetAgentService.updateHatchetAgent(agent1);
								} else {
									agentMoney = money4.add(money3);
									HatchetAgent agent1 = hatchetAgentService
											.selectHatchetAgentById(userRelation.getU4id());
									HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", moneyType, agentMoney, agent1.getAgentNo(), orderPayment.getOrderNo(),
											"10B", new Date());
									changeService.insertHatchetMoneyChange(moneyChange);
									agent1.setTotalMoney(agent1.getTotalMoney().add(agentMoney));
									hatchetAgentService.updateHatchetAgent(agent1);
								}
							}

							if (!"null".equals(userRelation.getU5id())) {
								HatchetAgent agent1 = hatchetAgentService
										.selectHatchetAgentById(userRelation.getU5id());
								if (!"null".equals(userRelation.getU4id())) {
									// 联创分润
									HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", moneyType, money5, agent1.getAgentNo(), orderPayment.getOrderNo(), "10B",
											new Date());
									changeService.insertHatchetMoneyChange(moneyChange);
									agent1.setTotalMoney(agent1.getTotalMoney().add(money5));
									hatchetAgentService.updateHatchetAgent(agent1);
								} else {
									if (!"null".equals(userRelation.getU3id())) {
										agentMoney = money5.add(money4);
										HatchetMoneyChange moneyChange = new HatchetMoneyChange(
												StringUtilsss.randomUUID(), "10B", moneyType, agentMoney,
												agent1.getAgentNo(), orderPayment.getOrderNo(), "10B", new Date());
										changeService.insertHatchetMoneyChange(moneyChange);
										agent1.setTotalMoney(agent1.getTotalMoney().add(agentMoney));
										hatchetAgentService.updateHatchetAgent(agent1);
									} else {
										agentMoney = money5.add(money4).add(money3);
										HatchetMoneyChange moneyChange = new HatchetMoneyChange(
												StringUtilsss.randomUUID(), "10B", moneyType, agentMoney,
												agent1.getAgentNo(), orderPayment.getOrderNo(), "10B", new Date());
										changeService.insertHatchetMoneyChange(moneyChange);
										agent1.setTotalMoney(agent1.getTotalMoney().add(agentMoney));
										hatchetAgentService.updateHatchetAgent(agent1);
									}

								}

							}

						}
					}
				}
				// 修改订单状态
				orderPayment.setSettleListStatus("10B");
				orderPayment.setUpdateTime(new Date());
				hatchetOrderPaymentService.updateHatchetOrderPayment(orderPayment);
			}
		}
		return AjaxResult.success("分润完成");
	}

//	/*
//	 * 递归寻找上级经纪人
//	 */
//	public HatchetMerchant findParentByLevel(HatchetMerchant mer, int plevel) {
//		int level = 0;
//		HatchetMerchant parent = null;
//		while (level < plevel) {
//			parent = hatchetMerchantService.getMerchantByPhoneOrLinkPhone(mer.getParentPhone());
//			if (parent != null) {
//				level = Integer.parseInt(parent.getLEVEL());
//				mer = parent;
//			}
//		}
//		return parent;
//	}
	
	/**
	 * 修改订单状态
	 * 
	 * @param increaseLimit
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateOrder")
	public Map<String, Object> updateOrder(@RequestParam("orderNo") String orderNo) {
		Map<String, Object> map = new HashMap<>();
		if ("".equals(orderNo)) {
			map.put("msg", "请输入订单号");
			map.put("status", BusinessStatus.FAIL);
			return map;
		}
		HatchetOrderPayment orderPayment = hatchetOrderPaymentService.selectHatchetOrderPaymentByOrder(orderNo);
		if (orderPayment != null) {
			orderPayment.setSTATUS("10B");
			int update =  hatchetOrderPaymentService.updateHatchetOrderPayment(orderPayment);
			if (update > 0) {
				map.put("msg", "修改成功");
				map.put("status", BusinessStatus.SUCCESS);
				return map;
			} else {
				map.put("msg", "修改失败");
				map.put("status", BusinessStatus.FAIL);
				return map;
			}
			
		}else {
			map.put("msg", "订单不存在，请确认订单号");
			map.put("status", BusinessStatus.FAIL);
			return map;
		}
	}
	
	
}
